<?php
// app/Controller/UsersController.php
class UsersController extends AppController
{

    var $uses = array(
        'User','LoginTrail','FailedLogin'
    );

    # Set the layout to use
    var $layout = 'user_layout';

    public function beforeFilter($param_array = null)
    {
        parent::beforeFilter();
        $this->Auth->allow('login', 'createLoginSession','logout', 'add');
    }

    public function index()
    {
        //$this->autoRender = false;
        //$this->autoLayout = false;
    }

    public function login()
    {
        if($this->Auth->user()){
            $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
        }

        if ($this->request->is('post')) {
            //$this->autoRender = false;
            //$this->autoLayout = false;
            $success = true;
           /* $attempt = $this->FailedLogin->validateLoginAttempts($this->request->data['User']['username']);
            if($attempt){
                $success = false;
                $this->Session->setFlash(__('Your account has been disabled, please contact your administrator.'));
            }*/
            //else{
                if ($this->Auth->login()) {
                    /** Check if account is disabled*/
                    $active = $this->Auth->user('active');
                    $user_type = $this->Auth->user('user_type');
                    $user_id = $this->Auth->user('id');
                    $login_session = $this->Auth->user('login_session');
                    $login_update_time = $this->Auth->user('login_update_time');
                    if ($active == 'Disabled') {
                        /** User is disable, Logout */
                        $success = false;
                        $this->Auth->logout();
                        $this->Session->setFlash(__('Your Account is Disabled.'));
                    }
                    //Handling Multiple user logging from the same account
                    if(empty($login_session)){//If both are empty, means the user logged out
                        $this->createLoginSession($user_id);
                    }
                    else{
                        //We still have to account for expired cookie  by using the time of last login update time
                        $rt = $this->timeIsUp($login_update_time);
                        if($rt['status']){
                            $this->createLoginSession($user_id);
                        }
                        else{
                            $success = false;
                            $this->Auth->logout();
                            //$this->Session->setFlash(__('Sorry, it seems you did not logout properly on your last login or the account is already being used. Please try again after '.$rt['min'].' mins.'));
                            $this->Session->setFlash(__('Sorry, it seems the account is  <br /> already being used.Please try again later'));
                        }
                    }
                }
                else {
                    //Log login attempt
                    $this->FailedLogin->save($this->sanitize(array(
                        'username'=>$this->request->data['User']['username'],
                        'ip_addr'=> $this->request->clientIp()
                    )));

                    $success = false;
                    $this->Session->setFlash(__('Invalid login Credentials'));
                }
            //}

            if ($success) { //Login Successful
                //Start to store the user id in the cookie for 1 day, let set cookie higher so we have less issue of users
                $save_trail = array(
                    'user_id'=>$this->Auth->user('id'),
                    'ip_addr'=> $this->request->clientIp()
                );
                $this->LoginTrail->save($this->sanitize($save_trail));
                $usr = $this->Auth->user();
                $usr['trail_id']= $this->LoginTrail->id;
                $this->Auth->login($usr);

                $this->Cookie->write('c_user_id',  $this->Auth->user('id'),false,3600 * 24);
                $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
            }
        }

        //May want to get the company info here
        $title_for_layout = 'memento';
        $this->layout = 'login_layout';

        $this->set(compact('title_for_layout'));
    }


    public function logout()
    {
        $user_id = $this->Auth->user('id');
        $trail_id = $this->Auth->user('trail_id');
        $path =  '/';
        //$this->clearLoginSession($user_id,$trail_id);
        $this->Session->destroy();
        $this->redirect($this->Auth->logout().$path);
    }



    private function createLoginSession($id) {
        $login_session = $this->randomString(50);
        $data['login_session'] = $login_session;
        $this->User->save($this->sanitize(array(
            'id'=>$id,
            'login_session' =>$login_session,
            'login_update_time'=>"'".date('Y-m-d H:i:s')."'"
        )));
        $this->Session->write('log_session', $login_session);
        return $data;
    }

    private function clearLoginSession($id,$trail_id) {
        $this->User->save($this->sanitize(array(
            'id'=>$id,
            'login_session' =>'',
            //'login_update_time'=>''
        )));

        $this->LoginTrail->save($this->sanitize(array(
            'id'=>$trail_id,
            'logout' =>date('Y-m-d H:i:s'),
            //'login_update_time'=>''
        )));
    }


    function timeIsUp($smaller_date){
        $old_datetime_arr = explode(' ',$smaller_date);
        $old_date = $old_datetime_arr[0];
        $old_time = $old_datetime_arr[1];
        $old_time_arr = explode(':',$old_time);
        $old_hour = $old_time_arr[0];
        $old_min = $old_time_arr[1];

        $now_data = date('Y-m-d');
        $now_hour = date('H');
        $now_min = date('i');

        $rt = array('status'=>true,'min'=>0);

        if(strtotime($now_data) > strtotime($old_date)){
            //It's been more than 30 min hesnce allow login
            return $rt;
        }

        if(strtotime($now_data) == strtotime($old_date)){
            if($now_hour > $old_hour){
                //Again more than an hour
                return $rt;
            }
            elseif($now_hour == $old_hour){
                $min = $now_min - $old_min;
                if($min >= 30 ){
                    return $rt;
                }
                else{
                    return array('status'=>false,'min'=> 30 - $min);
                }
            }
        }
    }


    /**
     * This function is for making some changes to the user profile
     * @name profile
     * @param void
     * @return void
     * @access public
     */
    public function profile()
    {
        //debug($this->Auth->user());
        if ($this->request->is('post')) {
            $this->User->id = $this->Auth->user('id'); // on edit
            $user_save = array('User' => $this->request->data['User']);

            if (!empty($this->request->data['User']['password'])) {
                $user_save['User']['password'] = AuthComponent::password($this->request->data['User']['password']);
            } else {
                unset($user_save['User']['password']);
            }

            $res = $this->User->save($this->sanitize($user_save['User']));

            if ($res) {
                $user = $this->User->find('first', array(
                    'conditions' => array('User.id' => $this->Auth->user('id')),
                    'recursive' => -1
                ));
                $user = $user['User'];
                $this->Auth->login($user);
                $this->Session->setFlash('Profile info has been updated !');
                $this->Session->write('process_error', 'no');
            }
            else {
                $this->Session->setFlash('Sorry, Profile info could not be updated');
                $this->Session->write('process_error', 'yes');
            }

            $this->redirect(array('action' => 'profile'));
        }

        $page_title = 'Edit Profile';
        $page_summary = 'Change you profile information';
        $page_icon = 'iconfa-pencil';
        $controller = $this;
        $this->set(compact('page_title','page_summary','page_icon','controller'));
    }

    /**
     * This function redirects the user to his appropriate page after login
     * @name signIn
     * @param void
     * @return void
     * @access public
     */
    function action_after_login()
    {
        $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
    }

    /*public function welcome() {
        $this->autoLayout = false;
        $this->autoRender = false;
        if ($this->request->is('ajax')) {
            $save = array(
                'User'=>array(
                    'id'=>$this->Auth->user('id'),
                    'shown_welcome'=>'y'
                )
            );
            if ($this->User->save($this->sanitize($save['User']))) {
                $user = $this->User->find('first', array(
                    'conditions' => array('User.id' => $this->Auth->user('id')),
                    'recursive' => -1
                ));
                $user = $user['User'];
                if ($this->Auth->user('user_type') == 'bdc') {
                    $user_type = $this->BdcUser->find('first', array(
                        'conditions' => array('BdcUser.user_id' => $this->Auth->user('id')),
                        'recursive' => -1
                    ));
                    $user['BdcUser'] = $user_type['BdcUser'];
                } elseif ($this->Auth->user('user_type') == 'omc') {
                    $user_type = $this->OmcUser->find('first', array(
                        'conditions' => array('OmcUser.user_id' => $this->Auth->user('id')),
                        'recursive' => -1
                    ));
                    $user['OmcUser'] = $user_type['OmcUser'];
                }
                $this->Auth->login($user);
                return json_encode(array('code' => 0, 'msg' => 'Data Saved!'));
            } else {
                return json_encode(array('code' => 1, 'msg' => 'Some errors occurred.'));
            }
        }
    }*/

    public function add() {
        if( $this->request->is('post') ) {
            //echo debug($this->request->data);
            $this->User->create();
            if( $this->User->save($this->request->data) ) {
                echo 'The user has been saved';
                $this->redirect(array('action' => 'index'));
            } else {
                echo 'The user could not be saved. Please, try again.';
            }
        }
    }

}